<template>
	<view>
    <view class="chat-container">
        <view class="payment-overlay" id="paymentOverlay" v-if="showBuy">
            <view class="payment-message">李苗老师试聊结束 20元/30分钟咨询</view>
            <button class="payment-button" @click="rechargeMembership">支付20元</button>
        </view>
        <view class="chat-header">
			<u-row gutter="16">
				<u-col span="1">
				</u-col>
				<u-col span="2">
					<u-image shape="circle" src="https://share-1259268558.cos.ap-shanghai.myqcloud.com/WX20240629-212527%402x.png" mode="aspectFill" alt="Profile Picture"></u-image>
				</u-col>
				<u-col span="4">
					<!-- <u-image shape="circle" src="https://share-1259268558.cos.ap-shanghai.myqcloud.com/WX20240629-212527%402x.png" mode="aspectFill" alt="Profile Picture"></u-image> -->
				</u-col>
				<u-col span="7">
					<view class="info-container">
						<view class="intro">李苗 好评率99%</view>
						<view class="intro">已咨询3000+人次</view>
						<view class="intro">到期时间:</view>
						<u-count-down :time="timestamp" format="HH:mm:ss"></u-count-down>
					</view>
				</u-col>
			</u-row>
		</view>
		
		<scroll-view scroll-y="true" class="message-list" ref="scrollView" id="commentContainer" :scroll-top="commentScrollTop">	
		<view class="chat-box" id="commentContent">
			<view v-for="(message, index) in messages" :key="index" class="chat-message" :class="message.class" >
			  <view v-if="message.content.startsWith('https')" class="chat-bubble" :class="message.class">
			     <u-image :src="message.content" alt="聊天图片" width="100%" height="300rpx" mode="widthFix" style="width: 100px; height: 100px;"></u-image> <!-- 这里设置了图片宽高样式，可按需调整 -->
			  </view>
			  <view v-else class="chat-bubble" :class="message.class">
				<zero-markdown-view :markdown="message.content" class="markdown-content"></zero-markdown-view>
			  </view>
			</view>
		</view>
		</scroll-view>
        <view class="chat-input">
            <input type="text" id="userInput" placeholder="" v-model="userInput" v-if="this.sending == false">
			<input type="text" id="userInput" placeholder="回复中, 请勿在发送" v-model="userInput" v-else="this.sending == false">
            <button @click="sendMessage()" id="sendButton" v-if="this.sending == false">发送</button>
			<button id="sendButtonDisable" v-else="this.sending == false" style="background-color: gray;">发送</button>
            <button class="record-button" id="recordButton" style="display: none;">Hold to Talk</button>
            <button class="toggle-button" id="toggleButton" style="display: none;">Switch to Text</button>
        </view>
    </view>
	</view>
</template>
<script>
	let isRecording = false;
	let mediaRecorder;
	let audioChunks = [];
	let messageCount = 0;
	let serverFinTim = localStorage.getItem('finish_time');
	// let markid = getQueryString('mark_id');
	// console.log(markid);

	// document.addEventListener('DOMContentLoaded', () => {
	// 	const timestamp = parseInt(new Date().getTime() / 1000);
	// 	let orderNo = getQueryString('order_no');
	// 	if ((serverFinTim == null || serverFinTim - timestamp < 0) && orderNo != null) {
	// 		console.log(123);
	// 		setTimeout(() => {
	// 			getOrderResult(orderNo);
	// 		}, 1000);
	// 	}
	// 	loadChatHistory();
	// 	console.log(serverFinTim - timestamp);
	// 	if (serverFinTim != null && serverFinTim - timestamp > 0) {
	// 		console.log('finish_time');
	// 		startCountdown(serverFinTim - timestamp);
	// 	}
	// });
import COS from 'cos-js-sdk-v5';
export default {
	data() {
	  return {
	    title: '充值提醒',
		content: '20元120张聊天记录图分析, 每次最多可以传入4张照片',
	    fileList1: [],
	    availableTimes: 0, // 可用次数
	    membershipExpiry: "", // 会员到期时间
	    showOverlay: false, // 控制浮层显示
	    analysisResult: "", // 分析结果
	    loading: false, // 控制加载提示
		orderNo: "",
		show: true,
		countdown: 60,
		userInput: '',
		commentScrollTop: 0,
		showBuy: false,
		messages: [],
		sending: false,
		id: 0,
		inputBuffer: [],
		timestamp: 0
	  };
	},
	onLoad(options) {
		this.id = options.id;
		this.handleWeChatCallback();
	},
	methods: {
		saveOpenID(openid) {
		  localStorage.setItem('openid', openid);
		},
		weChatLogin() {
		  const appId = 'wxad67b499443b7a4b';
		  const redirectUri = encodeURIComponent(window.location.href);
		  const weChatAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base#wechat_redirect`;
		  window.location.href = weChatAuthUrl;
		},
		async handleWeChatCallback() {
		  const urlParams = new URLSearchParams(window.location.search);
		  const code = urlParams.get('code');
		  if (code) {
		    try {
		      const response = await fetch(`https://data.bingdou.site/server/oneyuan/index/login?code=${code}`);
		      const data = await response.json();
		      console.log(data.data.open_id);
		      if (data.data.open_id) {
		        this.saveOpenID(data.data.open_id);
		        this.getAvailableTimes(data.data.open_id); // 获取可用次数和会员到期时间
		        window.history.replaceState({}, document.title, window.location.pathname);
		      } else {
		        console.error('Failed to get openid from server');
		      }
		    } catch (error) {
		      console.error('Error during WeChat login:', error);
		    }
		  } else {
		    this.checkOpenID();
		  }
		  
		  this.initChat();
		  this.getResponse();
		},
		async getAvailableTimes(openid) {
		  try {
		    const response = await fetch(`https://data.bingdou.site/server/oneyuan/index/getUserInfo?open_id=${openid}`);
		    const data = await response.json();
		    this.membershipExpiry = data.data.end_time;
		    console.log('可用次数:', this.availableTimes);
		    console.log('会员到期时间:', this.membershipExpiry);
		  } catch (error) {
		    console.error('请求可用次数和会员到期时间时出错:', error);
		  }
		},
		checkOpenID() {
		  const openid = localStorage.getItem('openid');
		  console.log(openid);
		  if (openid) {
		    this.getAvailableTimes(openid); // 获取可用次数和会员到期时间
		  } else {
		    this.weChatLogin();
		  }
		},
		initChat() {
			console.log("initchat");
			this.messages.push({"class":"bot", "content": "对方正在输入中..."})
			// this.sending = true;
			
			fetch('https://data.bingdou.site/server/oneyuan/index/xinLiChatInit', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json;charset=UTF-8'
				},
				body: JSON.stringify({
					"open_id": localStorage.getItem('openid'),
					"chat_id": this.id
				})
			})
			.then(response => response.json())
			.then(result => {
				this.messages.pop();
				// this.sending = false;
				if (result.code == 100) {
					this.showBuy = true;
				} else {
					this.messages.push({"class":"bot", "content":result.data});
					this.$nextTick(() => {
					    this.scrollToBottom()
					})
				}
			})
			.catch(error => {
				console.error('Error:', error);
			});
		},
	getOrderResult(orderNo) {
		fetch('https://data.bingdou.site/server/bingdouyanzhidypay/index/getOrderPayment', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json;charset=UTF-8'
			},
			body: JSON.stringify({
				"out_order_no": orderNo
			})
		})
		.then(response => response.json())
		.then(result => {
			console.log(result);
			if (result.code == 0) {
				localStorage.setItem('finish_time', result.create_time);
				window.location.reload();
			} else {
				console.error('No data field in response:', result);
			}
		})
		.catch(error => {
			console.error('Error:', error);
		});
	},
	//滚动到底部
	scrollToBottom() {
	    let query = uni.createSelectorQuery().in(this)
	    query.select('#commentContainer').boundingClientRect()
	    query.select('#commentContent').boundingClientRect()
		console.log(query);
	    query.exec((res) => {
	    //如果子元素高度大于父元素高度(显示高度)
		console.log(res);
	    if (res[1].height > res[0].height) {
	      //计算出二者差值就是需要滚动的距离
	       this.commentScrollTop = res[1].height - res[0].height
		   
	    }
	  })
	},
	
	getResponse() {
		setInterval(() => {
			// this.messages.push({"class":"bot", "content":"对方正在输入中..."});
			fetch('https://data.bingdou.site/server/oneyuan/index/regularResponse', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json;charset=UTF-8'
				},
				body: JSON.stringify({
					"open_id": localStorage.getItem('openid'),
					// "chat_id": this.id
				})
			})
			.then(response => response.json())
			.then(result => {
				// this.messages.pop();
				// this.sending = false;
				if (result.code == 100) {
					this.showBuy = true;
				} else {
					for (const item in result.data) {
						this.messages.push({"class":"bot", "content":result.data[item]});
						this.$nextTick(() => {
							this.scrollToBottom()
						})
						this.sleep(1500);
					}
				}
			})
			.catch(error => {
				console.error('Error:', error);
			});
		}, 3000);
	},

    saveMessageToBackup(role, content) {
		const chatHistoryBackup = JSON.parse(localStorage.getItem('chatHistoryBackup')) || [];
		chatHistoryBackup.push({ role, content });
		localStorage.setItem('chatHistoryBackup', JSON.stringify(chatHistoryBackup));
	},

	getQueryString(name) {
		var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
		var r = window.location.search.substr(1).match(reg);
		if (r != null) {
			return unescape(r[2]);
		}
	},

	async sendMessage() {
		// if (this.sending == true) {
			// return;
		// }
		const message = this.userInput.trim();

		if (message === '') return;

		messageCount++;


		this.messages.push({"class":"user", "content":message});

		this.saveMessageToBackup('user', message);
		this.inputBuffer.push(message);
		this.userInput = '';
		this.$nextTick(() => {
		    this.scrollToBottom()
		})
		
		this.fetchResponse(message);
	},

	async fetchResponse(message) {
		try {
			const response = await fetch('https://data.bingdou.site/server/oneyuan/index/botReplySend', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({ 
					"open_id": localStorage.getItem('openid'),
					"message": message
				})
			})
			.then(response => response.json())
			.then(result => {
				console.log(result);
				if (result.code == 100) {
					this.messages.pop();
					this.showBuy = true;
				} else {
					this.messages.push({"class":"bot", "content":result.data});
					this.$nextTick(() => {
					    this.scrollToBottom()
					})
				}
			})
			.catch(error => {
				console.error('Error:', error);
			});

			// const data = await response.json();
			// this.messages.pop();
			// this.sending = false; 
			// // typingIndicator.remove();
			// if (data.code == 100) {
			// 	this.showBuy = true;
			// } else {
			// 	for (const item in data.data) {
			// 		this.messages.push({"class":"bot", "content":data.data[item]});
			// 		this.$nextTick(() => {
			// 			this.scrollToBottom()
			// 		})
			// 		await  this.sleep(500);
			// 	}
			// }
		} catch (error) {
			console.error('Error:', error);
			// typingIndicator.remove();
		}
	},
	
	async sleep(ms) {
	    return new Promise((resolve) => {
	        setTimeout(resolve, ms);
	    });
	},
	
	async rechargeMembership() {
	  // 请求服务端获取微信支付参数
	  try {
	    const response = await fetch('https://data.bingdou.site/server/oneyuan/index/pay', {
	      method: 'POST',
	      headers: {
	        'Content-Type': 'application/json'
	      },
	      body: JSON.stringify({
	        open_id: localStorage.getItem('openid'),
			type: 2
	      })
	    });
	    const data = await response.json();
			  this.orderNo = data.data.order_no;
			  
			  if (typeof WeixinJSBridge == "undefined") {
			      if (document.addEventListener) {
			          document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
			      } else if (document.attachEvent) {
			          document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
			          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
			      }
			  } else {
			      this.onBridgeReady(data);
			  }
			} catch (error) {
			  console.error('请求支付参数时出错:', error);
			}
	},
	
	onBridgeReady(data) {
			  var that = this
			  WeixinJSBridge.invoke('getBrandWCPayRequest', {
			      "appId": data.data.appId,     //公众号ID，由商户传入     
			      "timeStamp": data.data.timeStamp,     //时间戳，自1970年以来的秒数     
			      "nonceStr": data.data.nonceStr,      //随机串     
			      "package": data.data.package,
			      "signType": "MD5",     //微信签名方式：     
			      "paySign": data.data.paySign,
			  },
			  function(res) {
			      if (res.err_msg == "get_brand_wcpay_request:ok") {
			          // 使用以上方式判断前端返回,微信团队郑重提示：
			          //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
			  		  that.pollPaymentResult();
			      }
			  });
	},
	cancel() {
			  this.show = false;
	},
	async pollPaymentResult() {
	  const pollInterval = 1000; // 轮询间隔时间（毫秒）
	  const maxAttempts = 20; // 最大轮询次数
	  let attempts = 0;
			const orderNo = this.orderNo;
	  const poll = async () => {
	    try {
	      const response = await fetch(`https://data.bingdou.site/server/oneyuan/index/getOrderPayment?order_no=${orderNo}`);
	      const data = await response.json();
	      if (data.code === 0) {
	        // 支付成功
	        // alert('充值成功');
	        this.getAvailableTimes(localStorage.getItem('openid')); // 更新会员信息
	        return;
	      } else if (data.code === 1) {
	        // 支付进行中，继续轮询
	        if (attempts < maxAttempts) {
	          attempts++;
	          setTimeout(poll, pollInterval);
	        } else {
	          alert('支付结果查询超时');
	        }
	      } else {
	        // 支付失败
	        alert('支付失败');
	      }
	    } catch (error) {
	      console.error('查询支付结果时出错:', error);
	      alert('查询支付结果时出错');
	    }
	  };
	
	  poll();
	}
	},
}
</script>


<style>
	html, body {
	    overflow-x: hidden;
	    width: 100%;
	    margin: 0;
	    padding: 0;
	    box-sizing: border-box;
	}
	body {
		font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
		background-color: #f5f5f5;
		margin: 0;
		padding: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
	}
	.message-list {
		flex-grow: 1; /* 占用所有可用空间 */
		overflow-y: auto; 
		margin-top: 15rpx;
	}
	.chat-container {
		margin-top: 3rpx;
		display: flex;
		  flex-direction: column;
		  height: 100%; 
	}
	.chat-header {
		background-color: #ececec;
		color: dimgray;
		/* padding: 10px 20px; */
		/* display: flex; */
		/* align-items: center; */
		/* display: flex; */
		/* justify-content: center; */
		/* margin-top: 10px; */
		/* margin-bottom: 1px; /* 添加底部间距 */
	}
	
	.chat-header .info-container {
		display: flex;
		flex-direction: column;
	}
	.chat-header .intro {
		font-size: 16px;
		margin: 5px 0;
	}
	.chat-header .intro:first-child {
		font-weight: bold;
	}
	.countdown-timer {
		font-size: 16px;
		font-weight: bold;
		color: white;
		margin-top: 5px;
	}
	.chat-box {
		flex: 1;
		overflow-y: auto;
		padding: 5px;
		display: flex;
		flex-direction: column;
	}
	.chat-message {
		margin: 5px 0;
		display: flex;
		flex-direction: column;
	}
	.chat-message.user {
		align-items: flex-end;
	}
	.chat-message.picture {
		align-items: flex-end;
		margin-bottom: 100rpx;
	}
	.chat-message.bot {
		align-items: flex-start;
	}
	.chat-bubble {
		max-width: 80%;
		padding: 3px 3px;
		border-radius: 20px;
		line-height: 1.5;
		margin-bottom: 2px;
	}
	.chat-bubble.user {
		background-color: limegreen;
		border-radius: 20px 20px 0 20px;
	}
	.chat-bubble.picture {
		border-radius: 20px 20px 0 20px;
	}
	.chat-bubble.bot {
		background-color: #fff;
		border: 1px solid #ececec;
		border-radius: 20px 20px 20px 0;
	}
	.chat-input {
		display: flex;
		padding: 10px;
		border-top: 1px solid #ececec;
		background-color: #fafafa;
		align-items: center;
	}
	.chat-input input {
		flex: 1;
		padding: 10px;
		border: 1px solid #ececec;
		border-radius: 20px;
		margin-right: 10px;
		font-size: 16px;
	}
	.chat-input button {
		padding: 0 20px;
		border: none;
		background-color: #007aff;
		color: white;
		border-radius: 20px;
		cursor: pointer;
		font-size: 16px;
		flex-shrink: 0;
		height: 40px;
	}
	.chat-input button.voice {
		margin-left: 10px;
	}
	.chat-input button:hover {
		background-color: #005bb5;
	}
	.record-button {
		flex: 1;
		padding: 10px;
		border: 1px solid #ececec;
		border-radius: 20px;
		margin-right: 10px;
		font-size: 16px;
		background-color: white !important;
		color: black !important;
		cursor: pointer;
		text-align: center;
	}
	.toggle-button {
		padding: 0 20px;
		border: none;
		background-color: #007aff;
		color: white;
		border-radius: 20px;
		cursor: pointer;
		font-size: 16px;
		height: 40px;
	}
	.toggle-button:hover {
		background-color: #005bb5;
	}
	.small-button {
		padding: 5px 10px;
		font-size: 12px;
		margin-top: 5px;
		background-color: #007aff;
		color: white;
		border: none;
		border-radius: 10px;
		cursor: pointer;
	}
	.small-button:hover {
		background-color: #005bb5;
	}
	.converted-text {
		background-color: #f1f1f1;
		border: 1px solid #ececec;
		border-radius: 10px;
		padding: 10px;
		margin-top: 5px;
		font-style: italic;
		color: #333;
	}
	.payment-overlay {
		display: flex;
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		justify-content: center;
		align-items: center;
		flex-direction: column;
		z-index: 10;
	}
	.payment-message {
		/* background-color: #ffffff; */
		padding: 20px;
		border-radius: 10px;
		text-align: center;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
		background: linear-gradient(90deg, #ff7e5f, #feb47b);
		margin-bottom: 20px;
		font-size: 18px;
		width: 80%;
		color: #333;
	}
	.payment-button {
		padding: 5px 30px;
		background: linear-gradient(90deg, #ff7e5f, #feb47b);
		color: white;
		border: none;
		border-radius: 30px;
		cursor: pointer;
		font-size: 18px;
		font-weight: bold;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
		transition: background 0.3s, box-shadow 0.3s;
	}
	.payment-button:hover {
		background: linear-gradient(90deg, #ff6a4a, #fd9c6e);
		box-shadow: 0 6px 15px rgba(0, 0, 0, 0.3);
	}
	.fixed-buttons {
		position: fixed;
		bottom: 100px;
		right: 20px;
		display: flex;
		flex-direction: column;
		gap: 10px;
	}
	.role-button, .upload-button {
		padding: 10px 20px;
		background-color: #007aff;
		color: white;
		border: none;
		border-radius: 20px;
		cursor: pointer;
		font-size: 14px;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
		transition: background 0.3s, box-shadow 0.3s;
	}
	.role-button:hover, .upload-button:hover {
		background-color: #005bb5;
	}
	.modal {
		display: none;
		position: fixed;
		z-index: 100;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		overflow: auto;
		background-color: rgba(0, 0, 0, 0.5);
		justify-content: center;
		align-items: center;
	}
	.modal-content {
		background-color: #fefefe;
		margin: 15% auto;
		padding: 20px;
		border: 1px solid #888;
		width: 80%;
		max-width: 400px;
		border-radius: 10px;
		text-align: center;
	}
	.close {
		color: #aaa;
		float: right;
		font-size: 28px;
		font-weight: bold;
	}
	.close:hover,
	.close:focus {
		color: black;
		text-decoration: none;
		cursor: pointer;
	}
	@media (max-width: 600px) {
		.chat-container {
			width: 100%;
			height: 100vh;
			border-radius: 0;
		}
		.chat-box {
			padding: 10px;
		}
		.chat-input input {
			font-size: 14px;
			padding: 8px;
		}
		.chat-input button {
			font-size: 14px;
			padding: 0 15px;
			height: 36px;
		}
		.record-button {
			padding: 8px;
			height: 36px;
		}
		.toggle-button {
			height: 36px;
		}
	}
</style>